package name.bingo.common.utils;
/**
 * create by yanbing on 2019/3/19 15:03
 */
import com.google.common.base.Optional;
import name.bingo.common.exception.JsonResponseException;
import name.bingo.common.exception.ServiceException;
import name.bingo.common.model.Response;

import java.util.Collections;

public class RespHelper {
    public RespHelper() {
    }

    public static <T> T or(Response<T> resp, T failValue) {
        return resp.isSuccess() ? resp.getResult() : failValue;
    }

    public static Boolean orFalse(Response<Boolean> resp) {
        return (Boolean)or(resp, Boolean.FALSE);
    }

    public static <T> T or500(Response<T> resp) {
        if (resp.isSuccess()) {
            return resp.getResult();
        } else {
            throw new JsonResponseException(500, resp.getError());
        }
    }

    public static <T> T orServEx(Response<T> resp) {
        if (resp.isSuccess()) {
            return resp.getResult();
        } else {
            throw new ServiceException(resp.getError());
        }
    }

    public static <T, D extends T> Response<T> ok(D data) {
        Response<T> resp = new Response();
        resp.setResult(data);
        return resp;
    }

    public static final class Map {
        public Map() {
        }

        public static <K, V> Response<java.util.Map<K, V>> empty() {
            return Response.ok(Collections.emptyMap());
        }
    }

    public static final class Opt {
        public Opt() {
        }

        public static <T> Response<T> unwrap(Response<Optional<T>> resp, String error) {
            if (resp.isSuccess()) {
                //return ((Optional)resp.getResult()).isPresent() ? Response.ok(((Optional)resp.getResult()).get()) : Response.fail(error);
                return ((Optional)resp.getResult()).isPresent() ? Response.ok((resp.getResult()).get()) : Response.fail(error);
            } else {
                return Response.fail(resp.getError());
            }
        }

        public static <T, D extends T> Response<Optional<T>> of(D data) {
            return Response.ok(Optional.of(data));
        }

        public static <T> Response<Optional<T>> absent() {
            return Response.ok(Optional.absent());
        }

        public static <T, D extends T> Response<Optional<T>> fromNullable(D data) {
            return Response.ok(Optional.fromNullable(data));
        }
    }
}